import Authorized from '@/utils/Authorized';
import { showMessage } from '@/utils/utils';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Drawer, Popconfirm,Dropdown, Menu } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType, ColumnsState } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import AdminCreateForm from './components/adminCreateForm';
import AdminUpdateForm, { FormValueType } from './components/adminUpdateForm';
import { AdminTableListItem, UpdateRoleParams } from './adminData.d';
import { queryAdmin, updateAdmin, addAdmin, removeAdmin, removeBatchAdmin, updateAdminRole, getAdminRoles, getAdminDetail } from './adminService';
import AdminRoleForm from './components/adminRoleForm';

/**
 * 添加管理员
 * @param fields
 */
const handleAdd = async (fields: AdminTableListItem) => {
    const hide = message.loading('正在添加');
    try {
        await addAdmin({ ...fields }).then(res=>{
            showMessage(res);
        });
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};

/**
 * 更新管理员
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('正在保存');
    try {
        await updateAdmin(fields).then(res=>{
            showMessage(res);
        });
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('保存失败请重试！');
        return false;
    }
};

/**
 *  批量删除管理员
 * @param selectedRows
 */
const handleRemove = async (selectedRows: AdminTableListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
        await removeBatchAdmin({
            ids: selectedRows.map((row) => row.adminId),
        }).then(res=>{
            showMessage(res);
        });
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

/**
 *  删除管理员
 * @param selectedRows
 */
const handleDelete = async (selectedRows: AdminTableListItem|AdminTableListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
        if(selectedRows instanceof Array){
            await removeBatchAdmin({
                ids: selectedRows.map((row) => row.adminId),
            }).then(res=>{
                showMessage(res);
            });
        }else{
            await removeAdmin({
                id: selectedRows.adminId,
            }).then(res=>{
                showMessage(res);
            });
        }
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

/**
 * 更多菜单
 */
const handleOtherMenu = async (item: AdminTableListItem) => {
    return item;
}

/**
 * 设置角色
 * @param item
 */
const handleUpdateRole = async (param: UpdateRoleParams) => {
    const hide = message.loading('正在保存');
    try {
        await updateAdminRole(param).then(res=>{
            showMessage(res);
        });
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('保存失败请重试！');
        return false;
    }
};


const AdminTableList: React.FC<{}> = () => {
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [updateRoleModalVisible, handleUpdateRoleModalVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [row, setRow] = useState<AdminTableListItem>();
    const [currentData, setCurrentData] = useState<AdminTableListItem>({});
    const [selectedRowsState, setSelectedRows] = useState<AdminTableListItem[]>([]);

    const columns: ProColumns<AdminTableListItem>[] = [
        {
            title: '主键',
            key: 'adminId',
            dataIndex: 'adminId',
            valueType: 'text',
            hideInTable: true,
            hideInForm: true,
            search: false,
        },
        {
            title: '用户名',
            key: 'adminName',
            dataIndex: 'adminName',
            valueType: 'text',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '用户名为必填项',
                    },
                ],
            },
            render: (dom, entity) => {
                return <a onClick={() => {
                    setRow(entity);
                }}>{dom}</a>;
            },
        },
        {
            title: '昵称',
            key: 'nickName',
            dataIndex: 'nickName',
            valueType: 'text',
        },
        {
            title: '头像',
            key: 'avatar',
            dataIndex: 'avatar',
            valueType: 'avatar',
            search: false,
        },
        {
            title: '手机',
            key: 'phone',
            dataIndex: 'phone',
            valueType: 'text',
            copyable: true,
        },
        {
            title: '真实姓名',
            key: 'realName',
            dataIndex: 'realName',
            valueType: 'text',
        },
        {
            title: '邮箱',
            key: 'email',
            dataIndex: 'email',
            valueType: 'text',
        },
        {
            title: '性别',
            key: 'gender',
            dataIndex: 'gender',
            filters: true,
            search: false,
            valueEnum: {
                1: { text: '男', status: 'Default' },
                2: { text: '女', status: 'Default' },
                0: { text: '未知', status: 'Default' },
            },
        },
        {
            title: '状态',
            key: 'status',
            dataIndex: 'status',
            hideInForm: true,
            filters: true,
            valueEnum: {
                0: { text: '禁用', status: 'Default' },
                1: { text: '启用', status: 'Success' },
            },
        },
        {
            title: '类型',
            key: 'userType',
            dataIndex: 'userType',
            filters: true,
            hideInForm: true,
            valueEnum: {
                0: { text: '后台账号', status: 'Default' },
                1: { text: '店铺账号', status: 'Default' },
            },
        },
        {
            title: '国家地区',
            key: 'country',
            dataIndex: 'country',
            valueType: 'text',
            search: false,
        },
        {
            title: '省',
            key: 'province',
            dataIndex: 'province',
            valueType: 'text',
            search: false,
        },
        {
            title: '市',
            key: 'city',
            dataIndex: 'city',
            valueType: 'text',
            search: false,
        },
        {
            title: '备注信息',
            key: 'remark',
            dataIndex: 'remark',
            valueType: 'textarea',
            ellipsis: true,
            copyable: true,
            search: false,
        },
        {
            title: '创建时间',
            key: 'createTime',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInForm: true,
            search: false,
        },
        {
            title: '最后登录时间',
            key: 'loginTime',
            dataIndex: 'loginTime',
            valueType: 'dateTime',
            hideInForm: true,
            search: false,
        },
        {
            title: '角色',
            key: 'roles',
            dataIndex: 'roles',
            valueType: 'text',
            hideInForm: true,
            search: false,
            hideInTable: true,
            renderText: (value,record) => {
                console.log('dom role',value,record);
                if(value && value instanceof Array){
                    const roles = value.map(item=>item.roleName);
                    return roles.join();
                }
                return '-';
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                record.adminId!=='1' &&
                <>
                    <Authorized authority={['admin', 'ums:admin:edit']} noMatch="">
                        <a
                            onClick={() => {
                                setCurrentData(record);
                                handleUpdateModalVisible(true);
                            }}
                        >
                            编辑
                        </a>
                    </Authorized>
                    <Authorized authority={['admin', 'ums:admin:delete']} noMatch="">
                        <Divider type="vertical" />
                        <Popconfirm
                            title="确定要删除?"
                            onConfirm={async ()=>{
                                await handleDelete(record)
                                actionRef.current?.reloadAndRest?.();
                            }}
                        >
                            <a href="#">删除</a>
                        </Popconfirm>
                    </Authorized>
                    <Authorized authority={['admin', 'ums:admin:edit']} noMatch="">
                        <Divider type="vertical" />
                        <Dropdown overlay={
                            <Menu>
                                <Menu.Item>
                                    <a onClick={() => {
                                        setCurrentData(record);
                                        handleUpdateRoleModalVisible(true);
                                    }}>
                                        角色
                                    </a>
                                </Menu.Item>
                                <Menu.Item>
                                    <a onClick={() => {
                                        handleOtherMenu(record);
                                    }}>
                                        其他
                                    </a>
                                </Menu.Item>
                            </Menu>
                        }>
                            <a>
                                更多 <DownOutlined />
                            </a>
                        </Dropdown>
                    </Authorized>
                </>
            ),
        }
    ];
    const [columnsStateMap, setColumnsStateMap] = useState<{
        [key: string]: ColumnsState;
    }>({
        adminName: {
            show: true,
        },
        password: {
            show: true,
        },
        phone: {
            show: true,
        },
        email: {
            show: false,
        },
        openId: {
            show: false,
        },
        nickName: {
            show: true,
        },
        realName: {
            show: true,
        },
        avatar: {
            show: false,
        },
        country: {
            show: false,
        },
        gender: {
            show: false,
        },
        province: {
            show: false,
        },
        city: {
            show: false,
        },
        remark: {
            show: false,
        },
        status: {
            show: true,
        },
        userType: {
            show: false,
        },
        roles: {
            show: false,
        },
        roleName: {
            show: false,
        },
        loginTime: {
            show: true,
        },
        parentId: {
            show: false,
        },
        createTime: {
            show: true,
        },
        creator: {
            show: false,
        },
        updateTime: {
            show: false,
        },
        modifier: {
            show: false,
        },
    });

    return (
        <PageContainer>
            <ProTable<AdminTableListItem>
                headerTitle="管理员"
                actionRef={actionRef}
                rowKey="adminId"
                search={{
                    labelWidth: 120,
                }}
                scroll={{ x: 1200 }}
                toolBarRender={() => [
                    <Authorized key="auth-add-adminId" authority={['admin','ums:admin:add']} noMatch=''>
                        <Button type="primary" onClick={() => handleModalVisible(true)}>
                            <PlusOutlined /> 新建
                        </Button>,
                    </Authorized>
                ]}
                request={(params, sorter, filter) => queryAdmin({ ...params, sorter, filter })}
                columns={columns}
                columnsStateMap={columnsStateMap}
                onColumnsStateChange={(map) => setColumnsStateMap(map)}
                rowSelection={{
                    onChange: (_, selectedRows) => setSelectedRows(selectedRows),
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            await handleRemove(selectedRowsState);
                            setSelectedRows([]);
                            actionRef.current?.reloadAndRest?.();
                        }}
                    >
                        批量删除
                    </Button>
                    <Button type="primary">批量操作</Button>
                </FooterToolbar>
            )}
            <AdminCreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
                <ProTable<AdminTableListItem, AdminTableListItem>
                    onSubmit={async (value) => {
                        const success = await handleAdd(value);
                        if (success) {
                            handleModalVisible(false);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    rowKey="adminId"
                    type="form"
                    columns={columns}
                />
            </AdminCreateForm>
            <AdminUpdateForm
                onSubmit={async (value: AdminTableListItem) => {
                    const success = await handleUpdate(value);
                    if (success) {
                        handleUpdateModalVisible(false);
                        setCurrentData({});
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    handleUpdateModalVisible(false);
                    setCurrentData({});
                }}
                updateModalVisible={updateModalVisible}
                currentData={currentData}
            />

            <AdminRoleForm
                onSubmit={async (value: UpdateRoleParams) => {
                    const success = await handleUpdateRole(value);
                    if (success) {
                        handleUpdateRoleModalVisible(false);
                        setCurrentData({});
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    handleUpdateRoleModalVisible(false);
                    setCurrentData({});
                }}
                roleModalVisible={updateRoleModalVisible}
                currentData={currentData}
            />

            <Drawer
                width={600}
                visible={!!row}
                onClose={() => {
                    setRow(undefined);
                }}
                closable={false}
            >
                {row?.adminName && (
                    <ProDescriptions<AdminTableListItem>
                        column={2}
                        title={row?.adminName}
                        request={async (params) => getAdminDetail(params)}
                        params={{
                            id: row?.adminId,
                        }}
                        columns={columns}
                    />
                )}
            </Drawer>
        </PageContainer>
    );
};

export default AdminTableList;
